// 数字转中文 万亿以下
const map = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
const units = ["", "十", "百", "千"];
const bigUnits = ["", "万", "亿"];
// 将小写数字转为大写数字
function transform(str) {
  let res = "";
  for (let i = 0; i < str.length; i++) {
    let d = map[str[i]];
    let u = units[str.length - i - 1];
    u = d === "零" ? "" : u;
    res += d + u;
  }
  // 处理连续零,和零在末尾时的情况
  res = res.replace(/零+/g, "零").replace(/零$/, "");
  return res;
}

const toChineseNumber = function (num) {
  // 先将金额分成4位一组的数组
  const parts = num
    .toString() // 将数字转成字符串
    .replace(/(?=(\d{4})+$)/g, ",") // 从后面开始，每4位添加一个“，”
    .split(",") // 将字符串以逗号分隔成数组
    .filter(Boolean); // 可以去掉数组的空字符串
  let res = ""; // 转换成大写字符
  parts.forEach((item, index) => {
    let r = transform(item);
    let u = bigUnits[parts.length - index - 1];
    if (r === "") {
      r = "零";
      u = "";
    }
    res += r + u;
  });
  res = res.replace(/零+/g, "零").replace(/零$/, "");
  return res;
};

// 生成随机数
const rand = function (m, n) {
  return Math.ceil(Math.random() * (n - m + 1)) + m - 1;
};

export { toChineseNumber, rand };
